﻿create procedure dbo.SaveAudience
(
		@Name varchar(255),
		@Description varchar(2000) = '',
		@AudienceID int = null OUTPUT,
		@PortalID int = 0
	)

AS

	DECLARE @iCount int
	
	IF @AudienceID = null
		BEGIN
			SET @iCount = (SELECT Count(Id) FROM dbo.Audience WHERE [Name] = @Name AND [SiteID] = @PortalID)
			
			IF @iCount = 0 
				BEGIN
					INSERT INTO dbo.Audience
		                      ([Name], Description, [SiteID])
					VALUES     (@Name,@Description, @PortalID)
					
					SET @AudienceID = SCOPE_IDENTITY()
				
				END
			ELSE
				BEGIN
					RAISERROR ('The Audience %s already exists in on the portal %d.', 16, 1, @Name, @AudienceID)
				END
		END
	ELSE
		BEGIN
			SET @iCount = (SELECT Count(Id) From dbo.Audience WHERE Id = @AudienceID)
					
			IF @iCount > 0
				BEGIN
					UPDATE    dbo.Audience
					SET              Name = @Name, Description = @Description, [SiteID] = @PortalID
					WHERE     (Id = @AudienceID)
				END
			ELSE
				BEGIN
					INSERT INTO dbo.Audience
		                      ([Name], Description, [SiteID])
					VALUES     (@Name,@Description, @PortalID)
			
					SET @AudienceID = SCOPE_IDENTITY()
				END
		END

	RETURN


